package net.wexoo.onlinedivelog.reusable.behaviour;

import static org.slf4j.LoggerFactory.getLogger;
import net.wexoo.onlinedivelog.view.util.NotificationPanel;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.form.FormComponent;

public class AjaxCSSClassAppender extends AjaxFormComponentUpdatingBehavior {
  private static final long serialVersionUID = 1L;

  private final String cssClass;
  private final NotificationPanel notificationPanel;

  public AjaxCSSClassAppender(NotificationPanel notificationPanel) {
    this("onblur", notificationPanel);
  }

  public AjaxCSSClassAppender(String event, NotificationPanel notificationPanel) {
    this(event, "", notificationPanel);
  }

  public AjaxCSSClassAppender(String event, String cssClass, NotificationPanel notificationPanel) {
    super(event);

    this.cssClass = cssClass;
    this.notificationPanel = notificationPanel;
  }

  @Override
  protected void onUpdate(AjaxRequestTarget target) {
    getLogger(getClass()).debug("on update called!");

    appendCSSClassAndUpdateComponent(target, "validation_success");
  }

  @Override
  protected void onError(AjaxRequestTarget target, RuntimeException e) {
    getLogger(getClass()).debug("on error called!");

    appendCSSClassAndUpdateComponent(target, "validation_error");
  }

  private void appendCSSClassAndUpdateComponent(AjaxRequestTarget target, String validationCSSClass) {
    getLogger(getClass()).debug("on appendCSSClassAndUpdateComponent called!");

    FormComponent<?> formComponent = getFormComponent();

    formComponent.add(new TemporaryAttributeAppender("class", cssClass + " " + validationCSSClass));

    target.add(formComponent);
    notificationPanel.refresh(target);
  }
}